﻿// This custom class derives from ContentMagager, and allows us to manually add or remove loaded objects
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Content;

namespace Organized
{
    public class IEContentManager : ContentManager
    {
        // just inherit from contentmanager and send the serviceProvider to the 
        public IEContentManager(IServiceProvider serviceProvider) : base(serviceProvider) { }

        // bool that sets wether we should keep objects that have been loaded, avoids loading same assets multiple times
        public bool PreserveAssets = true;

        // Keep a list of disposable assets and loaded assets
        List<IDisposable> disposable = new List<IDisposable>();
        Dictionary<string, object> loaded = new Dictionary<string, object>();

        // Override loading of assets so we can use our own functionality
        public override T Load<T>(string assetName)
        {
            //Create a new instance of the requested asset
            T r = this.ReadAsset<T>(assetName, RecordIDisposable);

            // if we are holding on to loaded assets, add it to the list 
            if (PreserveAssets && !loaded.ContainsKey(assetName))
                loaded.Add(assetName, r);

            // Return the loaded asset
            return r;
        }

        // Internal method to record disposable assets
        void RecordIDisposable(IDisposable asset)
        {
            //if we are holding on to loaded assets, add it to the disposing list
            if (PreserveAssets)
                disposable.Add(asset);
        }

        //Unload all content
        public override void Unload()
        {
            //dispose all disposable assets
            foreach (IDisposable disp in disposable)
                disp.Dispose();

            //clear all loaded assets
            loaded.Clear();
            disposable.Clear();
        }


        // Unload a specific asset
        public void Unload(string assetName)
        {
            // If the asset has been loaded
            if (loaded.ContainsKey(assetName))
            {
                //if it is disposable and it is in our list of disposable assets,
                if (loaded[assetName] is IDisposable && disposable.Contains((IDisposable)loaded[assetName]))
                {
                    IDisposable obj = disposable[disposable.IndexOf((IDisposable)loaded[assetName])];

                    //dispose the asset
                    obj.Dispose();
                    // remove it from the dispose list
                    disposable.Remove(obj);
                }

                // Take it off the list of loaded content
                loaded.Remove(assetName);
            }
        }

    }
}